package com.qst.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qst.beans.*;
import com.qst.service.impl.*;
import org.apache.commons.io.FileUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminUserServiceImpl adminUserService;

    @Autowired
    private CategoryServiceImpl categoryService;

    @Autowired
    private CategorySecondServiceImpl secondService;

    @Autowired
    private ProductServiceImpl productService;

    @Autowired
    private OrderServiceImpl orderService;

    @RequestMapping("/adminIndex")
    public String adminHome(){//到后台登录页
        return "admin/index";
    }

    @RequestMapping("/adminLogin")
    public String adminLogin(@Param("username") String username, @Param("password") String password, HttpServletRequest request){
//        System.out.println("username:"+username+",password:"+password);
        AdminUser adminUser = new AdminUser();
        adminUser.setUsername(username);
        adminUser.setPassword(password);
        System.out.println(adminUser);


        AdminUser adminBynamePwd = adminUserService.getAdminBynamePwd(adminUser);
        System.out.println(adminBynamePwd==null?"查询到的用户信息为空":adminBynamePwd);
        /*登录成功就到管理页，否则就回到登录页*/
        if (adminBynamePwd!=null) {
            request.getSession().setAttribute("enterAdmin",adminBynamePwd);
            return "/admin/home";
        }
        return "/admin/index";
    }


    /*-------以下是管理员对一级分类的操作*/

    @RequestMapping("/adminGetAllCate")
    public String getAllCategory(HttpServletRequest request){/*查找所有一级分类*/
        List<Category> categoryList = categoryService.findAll();
        request.setAttribute("cList",categoryList);

        return "admin/category/list";
    }

    @RequestMapping("/toAddCategory")
    public String toAddCategory(){
        System.out.println("进入添加一级分类页面");
        return "admin/category/add";
    }

    /*像数据库添加一级分类*/
    @RequestMapping(value="/addCategory_save" )
    public String addCategory(Category category){
        String cname = category.getCname();
        System.out.println("添加一级分类:"+cname);
        int i = categoryService.addCategory(category);
        if(i>0){
            System.out.println("添加"+category+"成功");
        }
        return "redirect: /admin/adminGetAllCate";
    }

    /*跳转到编辑一级分类页面*/
    @RequestMapping("/adminCategory_edit")
    public String editCategory(@Param("cid") Integer cid,HttpServletRequest request){
        /*从数据库中查找到此分类*/
        Category cByid = categoryService.findCByid(cid);
        request.setAttribute("category",cByid);
        return "admin/category/edit";
    }

    /*更新某一级分类*/
    @RequestMapping("/adminCategory_update")
    public String updateCategory(Category category){
        int i = categoryService.saveCategory(category);
        System.out.println(category.getCname()+"更新成功："+i);
        return "redirect: /admin/adminGetAllCate";
    }

    /*删除一级分类*/
    @RequestMapping(value ="/adminCategory_delete")
    public String deleteCategory(@Param("cid") Integer cid){
        /*删除一级分类之前先删除其下的二级分类*/
        List<CategorySecond> categorySecondList = categoryService.findCSByCid(cid);
        for (CategorySecond cs:categorySecondList
             ) {
            System.out.println("要删除的二级分类："+cs.getCsname());
            int i = secondService.deleteById(cs.getCsid());
            System.out.println("删除成功与否："+i);
        }
        /*最后删除一级分类*/
        int i = categoryService.deletByid(cid);
        System.out.println("一级分类删除成功与否："+i);
        return "redirect: /admin/adminGetAllCate";
    }




    /*-------以下是管理员对二级分类的操作*/
    @RequestMapping("/adminCategorySecond_findAllByPage")
    public String findCSByPage(@Param("page") Integer page,HttpServletRequest request){/*查找所有二级分类并分页*/
        PageUtils<CategorySecond> secondPageUtils = new PageUtils<>();
        //查找所有二级分类并分页
        int limit = 4;//每页分页记录数
        if (page==null)
            page = 1;
        PageHelper.startPage(page,limit);
        List<CategorySecond> allCS = secondService.findAllCS();
        PageInfo<CategorySecond> pageInfo = new PageInfo<>(allCS);//得到分页信息
        secondPageUtils.setPage(page);//当前页
        secondPageUtils.setList(allCS);//当前页的记录
        secondPageUtils.setTotalPage(pageInfo.getPages());//所有页数

        request.setAttribute("secondPageUtils",secondPageUtils);
        return "/admin/categorysecond/list";
    }

    /*进入添加二级商品类目页面*/
    @RequestMapping(value = "toAddCategorySecond")
    public String toAddCategorySecond(HttpServletRequest request){
        List<Category> categoryList = categoryService.findAll();
        request.setAttribute("categoryList",categoryList);
        return "/admin/categorysecond/add";
    }
    /*添加二级商品类目*/
    @RequestMapping(value = "addcategorySecond_save")
    public String addcategorySecond_save(CategorySecond categorySecond){
        System.out.println("所添加的二级目录"+categorySecond);
        int save = secondService.add(categorySecond);
        if (save>0)
            System.out.println("添加二级目录"+categorySecond+"成功");
        return "redirect: /admin/adminCategorySecond_findAllByPage";
    }






    /*------------------以下是管理员对商品的操作*/
    @RequestMapping(value = ("/adminProduct_findAllByPage") )
    public String findAllProByPage(@Param("page") Integer page,HttpServletRequest request){//查找商品并分页
        PageUtils<Product> productPageUtils = new PageUtils<>();
        int limit = 5;//每页的记录数
        if (page==null)
            page = 1;
        PageHelper.startPage(page,limit);
        List<Product> productList = productService.findAll();
        PageInfo<Product> pageInfo = new PageInfo<>(productList);//得到分页信息
        productPageUtils.setPage(page);//当前页
        productPageUtils.setList(productList);//当前页的记录数
        productPageUtils.setTotalPage(pageInfo.getPages());//所有的页数

        request.setAttribute("productPageUtils", productPageUtils);
        return "/admin/product/list";
    }


    @RequestMapping("/toAddProduct")
    public String toAddProduct(HttpServletRequest request){//跳转到添加商品页面
        //查找所有的二级分类
        List<CategorySecond> categorySecondList = secondService.findAllCS();
        request.setAttribute("csList",categorySecondList);
        return "/admin/product/add";
    }

    /*++++++添加商品++++*/
    @RequestMapping("/addProduct_save")
    public String addProduct(Product product,@RequestParam("upload") MultipartFile upload,HttpServletRequest request)throws Exception{

        product.setPdate(new Date());
        product.setIs_hot(0);
//        upload.getOriginalFilename();

        String realPath = request.getServletContext().getRealPath("/products");
        System.out.println(realPath);
//        String realPath = "D:/picture/upload";
        String originalFilename = upload.getOriginalFilename();
        File diskFile = new File(realPath + "//"+ originalFilename);
        System.out.println("目标文件:"+diskFile.getAbsolutePath());
        //将上传的实体文件复制到指定目录upload下
        upload.transferTo(diskFile);
        product.setImage("products/"+originalFilename);
//        product.setImage(realPath+originalFilename);

        System.out.println("收到的商品:"+product);
        //将信息保存到数据库
        int save = productService.save(product);
        System.out.println(product.getPname()+"保存是否成功:"+save);

        return "redirect: /admin/adminProduct_findAllByPage";
    }

    /*删除产品*/
    @RequestMapping("/adminProduct_delete")
    public String deleteProduct(@Param("pid") Integer pid, HttpServletRequest request){

        /* 删除上传文件图片*/
        Product product = productService.findById(pid);
        String path = product.getImage();
        if(path!=null) {
            String realPath = request.getServletContext().getRealPath("/" + path);
            File file = new File(realPath);
            file.delete();
        }
        /*删除数据库中的记录*/
        int deleteByid = productService.deleteByid(pid);

        return "redirect: /admin/adminProduct_findAllByPage";
    }


    /*跳转到某商品的编辑页面*/
    @RequestMapping("/adminProduct_edit")
    public String editProduct(@RequestParam("pid")Integer pid,HttpServletRequest request){
        /*根据商品ID获取某商品*/
        Product product = productService.findById(pid);
        System.out.println(product);
        request.setAttribute("product",product);
        /*所有二级分类*/
        List<CategorySecond> allCS = secondService.findAllCS();
        request.setAttribute("csList",allCS);

        return "/admin/product/edit";
    }

    /*保存商品修改信息,并重新上传*/
    @RequestMapping("/adminProduct_update")
    public String updateProduct(Product product, @RequestParam("upload")MultipartFile upload,
                                HttpServletRequest request)throws IOException {
        product.setPdate(new Date());
        if(upload.getSize() >=0){
            /*删除 目录中的文件，然后重新上传
             * 以及更新数据库中的记录*/
            String path = product.getImage();
            if (path != null){
                String realPath = request.getServletContext().getRealPath("/" + path);
                File file = new File(realPath);
                file.delete();
            }
            String realPath = request.getServletContext().getRealPath("/products");
            String originalFilename = upload.getOriginalFilename();
            File diskFile = new File(realPath + "//"+ originalFilename);
            //将上传的实体文件复制到指定目录upload下
            upload.transferTo(diskFile);
            product.setImage("products/"+originalFilename);
        }
        System.out.println("商品："+product);
        //将信息保存到数据库
        int save = productService.update(product);

        return "redirect: /admin/adminProduct_findAllByPage";
    }







    /*---------------以下是管理员对订单的管理，只能修改订单的状态*/
    @RequestMapping("/adminOrder_findAllByPage")
    public String findAllOrderPage(@Param("page") Integer page, HttpServletRequest request){
        PageUtils<Order> orderPageUtils = new PageUtils<>();
        if (page == null)
            page = 1;
        PageHelper.startPage(page,5);
        List<Order> allOrder = orderService.getAllOrder();
        PageInfo<Order> pageInfo = new PageInfo<>(allOrder);
        orderPageUtils.setList(allOrder);
        orderPageUtils.setPage(page);
        orderPageUtils.setTotalPage(pageInfo.getPages());

        request.setAttribute("orderPageUtils",orderPageUtils);
        return "/admin/order/list";
    }

    /*根据订单编号查找订单项*/
    @RequestMapping(value = "/adminOrderItem_findById")
    @ResponseBody
    public List<OrderItem> findItemsById(@RequestBody Order order, HttpServletRequest request){
        System.out.println("所需查找的订单项ID："+order.getOid());
        List<OrderItem> orderItemSet = orderService.findByOid(order.getOid());
        for (OrderItem orderitem: orderItemSet
             ) {
            System.out.println(orderitem);
        }
//        request.setAttribute("orderItems",orderItemSet);
//        return "/admin/order/orderItem";
        return orderItemSet;
    }

    @RequestMapping("/export_product_info")
    public void exportProductInfo(HttpServletResponse response)throws IOException{
        response.setCharacterEncoding("UTF-8");
        List<Product> productList = productService.findAll();
        System.out.println(productList);
        /*创建excel文件*/
        //创建excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建sheet页
        HSSFSheet sheet = wb.createSheet("商品信息表");
        //创建标题行
        HSSFRow titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("商品名称");
        titleRow.createCell(1).setCellValue("平台价格");
        titleRow.createCell(2).setCellValue("市场价格");
        titleRow.createCell(3).setCellValue("图片目录");
        titleRow.createCell(4).setCellValue("商品广告词");
        titleRow.createCell(5).setCellValue("销售量");
        titleRow.createCell(6).setCellValue("添加日期");
        titleRow.createCell(7).setCellValue("所属目录");

        for(Product product : productList){
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
            dataRow.createCell(0).setCellValue(product.getPname());
            dataRow.createCell(1).setCellValue(product.getShop_price());
            dataRow.createCell(2).setCellValue(product.getMarket_price());
            dataRow.createCell(3).setCellValue(product.getImage());
            dataRow.createCell(4).setCellValue(product.getIs_hot());
            dataRow.createCell(5).setCellValue(product.getPdesc());
            dataRow.createCell(6).setCellValue(product.getPdate());
            dataRow.createCell(7).setCellValue(product.getCsid());
        }
        // 设置下载时客户端Excel的名称
        String filename =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ".xls";
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + filename);
        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();

    }



}
